
import { Button, Space } from 'antd';
import React, { useEffect, useRef } from 'react'


type CanvasElementState = HTMLCanvasElement | null;
interface CoordinateState {
  x: number;
  y: number;
}
type EventsType = 'begin' | 'move' | 'end';


const Basic = () => {

  const drawFlag = useRef<boolean>(false);
  const cnavasFlag = useRef<CanvasRenderingContext2D | null>(null)
  const firstFlag = useRef<boolean>(true);

  const beginDraw = () => {
    drawFlag.current = true;
  }

  // 画图
  const drawImage = (point: CoordinateState, type: EventsType) => {

    const { current: ctx } = cnavasFlag;
    const { x, y } = point;
    if (ctx) {


      if (!firstFlag.current) {
        ctx.lineTo(x, y);

      }

      if (type === 'begin' && firstFlag.current) {
        ctx.moveTo(x, y);
        firstFlag.current = false;
      }
      // 双击
      if (type === 'end') {
        // 闭合
        ctx.closePath();
        // ③绘制
        ctx.stroke();
        drawFlag.current = false;
        firstFlag.current = true;
      }

    }


  }

  const startDraw = (e: MouseEvent, type: EventsType) => {
    if (drawFlag.current) {
      const x = e.offsetX; // 鼠标落下时的X
      const y = e.offsetY; // 鼠标落下时的Y
      drawImage({ x, y }, type)
    }
  }

  // 给canvas画布添加事件
  const addCanvasEvents = () => {
    const canvasEle: CanvasElementState = document.querySelector('#myCanvas');

    if (canvasEle) {
      const ctx = canvasEle.getContext('2d');

      if (ctx) {
        ctx.beginPath();
        ctx.strokeStyle = '#ff0000';
        cnavasFlag.current = ctx;
      }
      /**
       * 绑定点击事件
       */
      canvasEle.addEventListener('mousedown', e => {
        startDraw(e, 'begin');
      });
      /**
       * 绑定双击事件
       */
      canvasEle.addEventListener('mouseup', e => {
        startDraw(e, 'end');
      });

      /**
       * 绑定鼠标移动事件
       */
      canvasEle.addEventListener('mousemove', e => {
        startDraw(e, 'move');
      });

    }
  }


  useEffect(() => {
    addCanvasEvents();



  }, [])

  return (
    <div>

      <Space size="small" direction="horizontal">
        <Button
          type="primary"
          onClick={() => {
            beginDraw();
          }}
        >
          画不规则线条
        </Button>
        <Button
          type="primary"
          onClick={() => {
            beginDraw();
          }}
        >
          矩形
        </Button>
        <Button
          type="primary"
        // onClick={() => {
        //   clearRec();
        // }}
        >
          清除
        </Button>
      </Space>
      <canvas
        id='myCanvas'
        width={800}
        height={600}
        style={{ border: '1px solid red', marginTop: 24 }} />
    </div>
  )
}

export default Basic;